package com.kt.spring;

import java.io.File;
import java.net.URL;

public class KtApplicationContext {

    private AppConfig appConfig;

    public KtApplicationContext(AppConfig appConfig) {
        this.appConfig = appConfig;
        ComponentScan componentScan = this.appConfig.getClass().getDeclaredAnnotation(ComponentScan.class);
        String path = componentScan.value();
        System.out.println(path);
        this.loadComponent(path);
    }


    private void loadComponent(String path) {
        String pathDir = path.replace(".", "/");
        URL url = KtApplicationContext.class.getClassLoader().getResource(pathDir);
        if (url == null) {
            return;
        }
        String classPath = KtApplicationContext.class.getClassLoader().getResource(".").getFile();
        this.resolvePackage(url.getPath(), classPath);
    }

    private void loadClass(File file, String classPath) {
        int filePathLength = file.getPath().length();
        String className = file.getPath().substring(classPath.length() - 1, filePathLength - 6);
        System.out.println(className);
        ClassLoader classLoader = KtApplicationContext.class.getClassLoader();
        try {
            Class<?> clazz = classLoader.loadClass(className.replace("\\", "."));
            if (clazz.isAnnotationPresent(Component.class)) {
                clazz.newInstance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void resolvePackage(String packageDir, String classPath) {
        File file = new File(packageDir);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile() && f.getName().endsWith(".class")) {
                this.loadClass(f, classPath);
            } else {
                this.resolvePackage(packageDir + "/" + f.getName(), classPath);
            }
        }
    }
}
